import React, { useEffect, useState } from 'react';
import { View, Text, Image } from '@tarojs/components';
import './BottomNavigation.scss';
import Taro from "@tarojs/taro";
import home from '@/assets/icons/home.png';
import homeFill from '@/assets/icons/home-fill.png';
import community from '@/assets/icons/community.png';
import communityFill from '@/assets/icons/community-fill.png';
import plus from '@/assets/icons/plus.png';
import plusFill from '@/assets/icons/plus-fill.png';
import message from '@/assets/icons/message.png';
import messageFill from '@/assets/icons/message-fill.png';
import user from '@/assets/icons/user.png';
import userFill from '@/assets/icons/user-fill.png';

// 图片映射表
const iconMap = {
  home,
  homeFill,
  community,
  communityFill,
  plus,
  plusFill,
  message,
  messageFill,
  user,
  userFill,
};

interface BottomNavigationProps {
  onTabChange: (index: number) => void;
}

const BottomNavigation: React.FC<BottomNavigationProps> = ({ onTabChange }) => {
  // 从本地存储中读取选中的索引，如果没有则默认是 0
  const [selectedIndex, setSelectedIndex] = useState<number>(() => {
    const storedIndex = Taro.getStorageSync('selectedTabIndex');
    return storedIndex!== null? parseInt(storedIndex, 10) : 0;
  });

  const icons = [
    { name: '首页', icon: 'home', selectedIcon: 'homeFill', index: 0, path: '/pages/home/index' },
    { name: '社区', icon: 'community', selectedIcon: 'communityFill', index: 1, path: '/pages/community/index' },
    { name: '', icon: 'plus', selectedIcon: 'plusFill', index: 2, path: '/pages/plus/index' },
    { name: '消息', icon: 'message', selectedIcon: 'messageFill', index: 3, path: '/pages/message-list/index' },
    { name: '我的', icon: 'user', selectedIcon: 'userFill', index: 4, path: '/pages/user/index' }
  ];

  useEffect(() => {
    // 当选中的索引变化时，将其保存到本地存储
    Taro.setStorage({
      key: 'selectedTabIndex',
      data: selectedIndex.toString()
    });
  }, [selectedIndex]);

  const handleTabClick = (index: number, path: string) => {
    console.log('1',  path);
    setSelectedIndex(index);
    onTabChange(index);
    Taro.switchTab({
      url: path,
    });
  };

  return (
    <View className="bottom-navigation">
      {icons.map((item)  => (
        <View
          key={item.index}
          className={`${item.index!==  2? 'tab-item' : 'tab-items'} ${selectedIndex === item.index?  'active' : ''}`}
          onClick={() => handleTabClick(item.index,  item.path)}
        >
          <Image
            className={`${item.index!==  2? 'tab-icon' : 'tab-icons'}`}
            src={selectedIndex === item.index?  iconMap[item.selectedIcon]  : iconMap[item.icon]}
          />
          {item.name!==  '' && <Text className="tab-label">{item.name}</Text>}
        </View>
      ))}
    </View>
  );
};

export default BottomNavigation;
